package hu.stud.uszeged.inf.prf.prftrac.session;

import hu.stud.uszeged.inf.prf.prftrac.entity.User;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

@Name("authenticator")
public class Authenticator
{
    @Logger private Log log;

    @In private Identity identity;
    @In private Credentials credentials;
    @In(value = "#{entityManager}")
    private EntityManager em;
    @In(value = "#{userHome}")
    private UserHome userHome;
    

    public boolean authenticate()
    {
        log.info("authenticating {0}", credentials.getUsername());
//        //write your authentication logic here,
//        //return true if the authentication was
//        //successful, false otherwise
//        if ("admin".equals(credentials.getUsername()))
//        {
//            identity.addRole("admin");
//            log.info("logged in: {0}", identity.isLoggedIn());
//            return true;
//        }
//        return false;
        if (credentials.getUsername().equals("admin") 
        		&& credentials.getPassword().equals("admin")){
        	identity.addRole("admin");
        	
        	User u = new User();
        	u.setRole("admin");
        	userHome.setInstance(u);
        	return true;
        }
        Query q = em.createQuery("from User us where us.nickName= :nick and us.password = :pass");
        q.setParameter("nick", credentials.getUsername());
        q.setParameter("pass", credentials.getPassword());
        User u = (User)q.getSingleResult();
        
        if (u != null) {
        	if (u.getRole().equals("Administrator")) {
        		identity.addRole("admin");
        	} else {
        		identity.addRole("member");
        	}
        	log.info("logged in: {0}", identity.isLoggedIn());
        	log.info("Project: {0}", u.getProject().getName());
        	userHome.setInstance(u);
        	return true;
        } else {
        	return false;
        }
    }

}
